#include<iostream>
#include<unistd.h>
#include<pthread.h>
using namespace std;
#define NUM 5
class Ticket
{
public:
    Ticket() :tickets(1000) 
    {
        pthread_mutex_init(&mtx,NULL);
    }
    ~Ticket(){
        pthread_mutex_destroy(&mtx);
    }
    bool GetTicket() //返回值:是否还有票
    {
        bool res = true;//res是线程内部的局部变量,在线程的私有栈中, 并不是共享变量
        pthread_mutex_lock(&mtx); //访问临界区之前先申请锁
        if(tickets > 0)
        {
            usleep(1000);
            cout << "我是 ["<<pthread_self() <<"] 我要抢的票为：" << tickets<<endl;
            tickets--;
        }
        else
        {
            res = false;
            cout << "票已经被抢光了！" << endl;
        }
        pthread_mutex_unlock(&mtx); 
        return res;
    }
private:
    int tickets; //ticket是被多个执行流同时访问的临界资源 
    pthread_mutex_t mtx;
};
void* Rountinue(void* arg)
{
    Ticket* t = (Ticket*)arg;
    while(1)
    {
        if(!t->GetTicket())
            break;
    }
}
int main()
{
    //0.创建对象
    Ticket* t = new Ticket;
    //1.创建NUM个线程
    pthread_t tid[NUM];
    for(int i = 0;i<NUM;i++)
    {
        char* buf = new char[32];
        pthread_create(&tid[i],NULL,Rountinue,(void*)t); //把对象作为例程函数的参数
    }
    //2.进行线程等待
    for(int i = 0;i<NUM;i++)
        pthread_join(tid[i],nullptr);
    return 0;
}